
// a range slider with draggable range body, overriding the default behavour of snapping an endpoint to the mouse.
$.fn.rangeSlider = function(slider_opts){
  return $(this).each(function() {
    console.info('initializing range slider');
    var $slider = $(this);
    $(".ui-slider-range,.ui-slider-handle",$slider).unbind();    
    $slider.slider(slider_opts);

    // allow user to drag the slider body.
    var ui_slider_memory;
    
    ui_slider_val = function(x) {
      offset = $slider.offset();
      width = $slider.width();
      return Math.floor($slider.slider('option','min') + ($slider.slider('option','max')
        -$slider.slider('option','min'))*(x-offset.left)/width);
    };
    ui_slider_drag = function(evt) {
      //distance from grab point.
      
      delta = ui_slider_val(evt.pageX) - ui_slider_memory.orig_grab;

      new_start = Math.floor(CE.UTIL.constrain($slider.slider('option','min'),ui_slider_memory.orig_start + delta,$slider.slider('option','max')));
      new_end = Math.floor(CE.UTIL.constrain($slider.slider('option','min'),ui_slider_memory.orig_end + delta,$slider.slider('option','max')));
      
      /* only update if a change has been made, since this may trigger expensive events. */
      upd_end = new_end != $slider.slider("values",1) && ui_slider_memory.move_right_handle; // whether to update 2nd endpoint.
      if (new_start != $slider.slider("values",0) && ui_slider_memory.move_left_handle) {
        $slider.slider("values",0,new_start);
        if (upd_end) {CE.skip_next_refresh = true;}
      }
      if (upd_end) {
        $slider.slider("values",1,new_end);
      }
	  
      return false; 
    };
    ui_slider_stop = function(evt) {
      $().unbind('mouseup',ui_slider_stop).unbind('mousemove',ui_slider_drag);
      return false;
    };
    
    $(".ui-slider-range,.ui-slider-handle",$slider).bind('mousedown', function(evt){
      $().bind('mousemove',ui_slider_drag).bind('mouseup',ui_slider_stop);
      ui_slider_memory = {
	      move_left_handle:true,
		    move_right_handle:true,
        orig_start:$slider.slider("values",0),
        orig_end:$slider.slider("values",1),
        orig_grab:ui_slider_val(evt.pageX)
      };
      //console.log(ui_slider_memory);
		  if (this == $(".ui-slider-handle",$slider).get(0)) ui_slider_memory.move_right_handle = false;
		  else if (!$(this).hasClass("ui-slider-range")) ui_slider_memory.move_left_handle = false;
      return false;
    });
  });
};

